const { Store } = require("koa-session2");

class RedisStore extends Store {

    /*
     * @params db: mongoose数据模型
     */
    constructor(db) {
        super();

        // 建立仓库
        this.store = db
        
    }

    /* 查询session
     * @params sid: 哨兵
     * @return data: 缓存数据
     */
    async get(sid, ctx) {

        let data = []

        await this.store.find({sid}, (err, dbData) =>{

            if(err){console.log(err)}
            data = dbData
            
        })

        return Array.isArray(data) && !data.length  ? false : data;
    }


    /* 添加session
     * @params session: 配置session 缓存数据
     * @params sid: 哨兵 
     * @params maxAge 有效期 默认 10mine 具体指以session 中间件配置为准
     * @return sid
     */
    async set(session, { sid =  this.getID(24), maxAge = 600000 } = {}, ctx) {

        let _this = this
        let maxNum = 0

        // 防碰撞
        while( await _this.has(sid) && maxNum < 10 ){
            maxNum++
            sid =  this.getID(24)
        }

        if(maxNum >= 10){
            console.log('set session fail')
            return
        }        
        
        Object.assign(session, {sid, createAt: new Date()})
        
        await this.store.create(session, (err) =>{

            if(err){ console.log(err); return }
            
            let time = setTimeout(() =>{

                _this.destroy(sid)
                
            }, maxAge)
            
        })

        
        return sid;
    }

    /* 删除session
     * @params sid: 哨兵
     * @return success：boolean 操作是否成功
     */
    async destroy(sid, ctx) {

        let success = true
        
        await this.store.remove({sid}, (err) =>{

            if(err){
                success = false
                console.log(err)
                return
            }

            console.log(`delete session: ${ sid }`)

        })

        return success
    }

    async has(sid){
         
        let data = await this.get(sid)
        return !!data;
    }
    
}

module.exports = RedisStore;